package softtech.app.secretcaller;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class ActivityLogin extends Activity {

	final String TAG = "ACTIVITY LOGIN";

	Context context;

	MenuItem mniActionLogout;

	ViewFlipper vflipMain;
	Animation slide_in_left, slide_out_right;

	DatabaseHandler db;

	DatabaseUser mUser;

	ViewAlertDialogManager mAlertDialog;
	
	ViewDialog vDialog;

	/**
	 * Login form
	 */

	// variable status of edittext
	boolean status_username = true;

	boolean status_password = true;

	boolean status_email = true;

	boolean status_phone = true;

	boolean status_secretkey = true;

	// Edittext login form
	EditText edtLoginUsername, edtLoginPassword;

	// TextView login form
	TextView tvLoginRegister, tvLoginForgotPassword;

	// Button login form
	Button btnLoginSubmit;

	/**
	 * Register Form
	 */

	// Edittext register form
	EditText edtRegisterUsername, edtRegisterPassword, edtRegisterRepassword,
			edtRegisterEmail, edtRegisterSecurityKey, edtRegisterPhone;

	// Radio Button register form
	RadioButton rabtnConfirm1, rabtnConfirm2, rabtnConfirm3, rabtnConfirm4;

	// Button Register form
	Button btnRegisterSubmit, btnRegisterBackToLogin;

	/**
	 * Security Form
	 */
	ArrayList<ImageButton> listSecurityImageButton;

	String securityPass;

	int securityInputValue;
	
	/**
	 * Copyright form
	 */
	
	LinearLayout	linearCopyright;
	
	TextView tvCancel;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		context = this;
		Log.e(TAG, "ONCREATE");
		setId();
		init();
		setFunctionForControl();
		startService();
	}
	
	/**
	 * start service and broadcast receive of application
	 */
	void startService(){
		context.startService(new Intent(context, ServiceDateTimeChange.class));
//		ControlPhoneAction.deleteShortCut(context, "kyniema4");
//		ControlPhoneAction.addShortcut(context, "kyniema4");
	}

	/**
	 * Init value of activity
	 */
	void init() {
		securityPass = "";
//		BroadcastListenSms receiver_SMS = new BroadcastListenSms();
//		registerReceiver(receiver_SMS, new IntentFilter(
//				"android.provider.Telephony.SMS_RECEIVED"));
		initViewFlipper();
		initDatabase();
	}

	/**
	 * Init Database and check login
	 */
	void initDatabase() {
		db = new DatabaseHandler(context);
		int id_login = checkLogin();
		Log.e(TAG, "ID =" + id_login);
		if (id_login >= 0) {
			mUser = db.getUser(id_login);
			if (mUser != null) {
				selectPage(2);
			} else {
				Log.e(TAG, "CHUA CO USER");
			}
		} else {
			return;
		}

	}

	/**
	 * Check Login - (-1) : if not login. - id_login : if logged in.
	 */
	int checkLogin() {
		int id = -1;
		ToolsSaveFile tsf = new ToolsSaveFile();

		String id_loggedin = tsf.LoadContentFile(context,
				ConstantsFileName.FILE_ID_LOG_IN);

		if (id_loggedin == null || id_loggedin.equals("")
				|| id_loggedin.length() == 0) {

			id = -1;
		} else {
			try {
				id = Integer.parseInt(id_loggedin);

			} catch (Exception e) {
				id = -1;
				e.printStackTrace();
			}
		}

		return id;
	}

	/**
	 * Set id for controls of activity
	 */
	void setId() {
		// Main form
		vflipMain = (ViewFlipper) findViewById(R.id.vflipMain);

		// Login form
		edtLoginUsername = (EditText) findViewById(R.id.edtLoginUsername);
		edtLoginPassword = (EditText) findViewById(R.id.edtLoginPassword);
		tvLoginRegister = (TextView) findViewById(R.id.tvLoginRegister);
		tvLoginForgotPassword = (TextView) findViewById(R.id.tvLoginForgotPassword);
		btnLoginSubmit = (Button) findViewById(R.id.btnLoginSubmit);

		// Register form
		edtRegisterUsername = (EditText) findViewById(R.id.edtRegisterUsername);
		edtRegisterPassword = (EditText) findViewById(R.id.edtRegisterPassword);
		edtRegisterRepassword = (EditText) findViewById(R.id.edtRegisterRepassword);
		edtRegisterEmail = (EditText) findViewById(R.id.edtRegisterEmail);
		edtRegisterSecurityKey = (EditText) findViewById(R.id.edtRegisterSecurityKey);
		edtRegisterPhone = (EditText) findViewById(R.id.edtRegisterPhone);
		btnRegisterSubmit = (Button) findViewById(R.id.btnRegisterSubmit);
		btnRegisterBackToLogin = (Button) findViewById(R.id.btnRegisterBackToLogin);

		// Security form

		rabtnConfirm1 = (RadioButton) findViewById(R.id.rabtnConfirm1);
		rabtnConfirm2 = (RadioButton) findViewById(R.id.rabtnConfirm2);
		rabtnConfirm3 = (RadioButton) findViewById(R.id.rabtnConfirm3);
		rabtnConfirm4 = (RadioButton) findViewById(R.id.rabtnConfirm4);

		listSecurityImageButton = new ArrayList<ImageButton>();
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber0));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber1));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber2));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber3));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber4));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber5));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber6));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber7));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber8));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber9));
		
		// set id for linear copyright
		linearCopyright = (LinearLayout) findViewById(R.id.linearCopyright);
		
		tvCancel = (TextView) findViewById(R.id.tvCancel);
		
	}

	/**
	 * Set function for controls of activity
	 */
	void setFunctionForControl() {
		setFunctionForLoginForm();
		setFunctionForRegisterForm();
		setFunctionForSecurityForm();
	}

	/**
	 * Set function for controls in login form
	 */
	void setFunctionForLoginForm() {
		btnLoginSubmit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (edtLoginUsername.getText().toString().length() < 8) {
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog.showAlertDialog(context, "Username error!",
							"Username must be more than 8 character length",
							false);
					return;
				}

				if (edtLoginUsername.getText().toString().length() >= 30) {
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog.showAlertDialog(context, "Username error!",
							"Username must be less than 30 character length",
							false);
					return;
				}

				if (edtLoginPassword.getText().toString().length() < 6) {
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog.showAlertDialog(context, "Username error!",
							"Password must be more than 6 character length",
							false);
					return;
				}

				if (edtLoginPassword.getText().toString().length() >= 30) {
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog.showAlertDialog(context, "Username error!",
							"Password must be less than 30 character length",
							false);
					return;
				}

				ConnectionDetector cd = new ConnectionDetector(context);
				if (!cd.isConnectingToInternet()) {
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog
							.showAlertDialog(
									context,
									"Internet error!",
									"Have no internet connection in your phone.",
									false);
					return;
				}

				LoginWithServer taskLoginWithServer = new LoginWithServer(
						edtLoginUsername.getText().toString(), edtLoginPassword
								.getText().toString());
				taskLoginWithServer.execute(null, null, null);
			}
		});

		tvLoginRegister.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.e(TAG, "tvLogin Click");
				// vflipMain.showNext();
				selectPage(1);
			}
		});

		tvLoginForgotPassword.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				OnClickListener clickOK = new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						ForgotPassword taskForgotPassword = new ForgotPassword(vDialog.txtCheckCode.getText().toString());
						taskForgotPassword.execute(null,null,null);
					}
				};
				
				vDialog = new ViewDialog(context,
						"Enter Your Email",
						"Enter your email to get password and security key",
						" OK ", " Cancel ", clickOK, null, "");
				vDialog.showDialog();
			}
		});
	}

	/**
	 * Set function for controls in register form
	 */
	void setFunctionForRegisterForm() {

		edtRegisterUsername.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {

				if (event.getAction() == MotionEvent.ACTION_DOWN
						&& !status_username) {

					status_username = true;

					edtRegisterUsername.setTextColor(Color.BLACK);
				}
				return false;
			}
		});

		edtRegisterPassword.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {

				if (event.getAction() == MotionEvent.ACTION_DOWN
						&& !status_password) {

					status_password = true;

					edtRegisterPassword.setTextColor(Color.BLACK);
				}
				return false;
			}
		});

		edtRegisterEmail.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {

				if (event.getAction() == MotionEvent.ACTION_DOWN
						&& !status_email) {

					status_email = true;

					edtRegisterEmail.setTextColor(Color.BLACK);
				}
				return false;
			}
		});

		edtRegisterPhone.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {

				if (event.getAction() == MotionEvent.ACTION_DOWN
						&& !status_phone) {

					status_phone = true;

					edtRegisterPhone.setTextColor(Color.BLACK);
				}
				return false;
			}
		});

		edtRegisterSecurityKey.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {

				if (event.getAction() == MotionEvent.ACTION_DOWN
						&& !status_secretkey) {

					status_secretkey = true;

					edtRegisterSecurityKey.setTextColor(Color.BLACK);
				}
				return false;
			}
		});

		btnRegisterSubmit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				ConnectionDetector cd = new ConnectionDetector(context);
				if (!cd.isConnectingToInternet()) {
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog.showAlertDialog(context, "Internet error!",
							"Can not Connect to Server", false);

					return;
				}

				// Check form here
				if (edtRegisterUsername.getText().toString().length() < 8) {
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog
							.showAlertDialog(
									context,
									"Username error!",
									"Username length must be more than 8 character length",
									false);
					return;
				}

				if (edtRegisterUsername.getText().toString().length() >= 30) {
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog
							.showAlertDialog(
									context,
									"Username error!",
									"Username length must be less than 30 character length",
									false);
					return;
				}

				if (edtRegisterPassword.getText().toString().length() < 6) {
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog
							.showAlertDialog(
									context,
									"Password error!",
									"Password length must be more than 6 character length",
									false);
					return;
				}

				if (edtRegisterPassword.getText().toString().length() >= 30) {
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog
							.showAlertDialog(
									context,
									"Password error!",
									"Password length must be less than 30 character length",
									false);
					return;
				}

				// if (edtRegisterRepassword.getText().toString().length() < 6)
				// {
				// mAlertDialog = new ViewAlertDialogManager();
				// mAlertDialog
				// .showAlertDialog(
				// context,
				// "Password error!",
				// "Re-enter password length must be 6 character length",
				// false);
				// return;
				// }

				if (!edtRegisterPassword.getText().toString()
						.equals(edtRegisterRepassword.getText().toString())) {
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog.showAlertDialog(context, "Password error!",
							"re-enter the password and password do not match",
							false);
					return;
				}

				if (edtRegisterEmail.getText().toString().length() < 10
						|| !isValidEmail(edtRegisterEmail.getText().toString())) {
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog.showAlertDialog(context, "Email!",
							"Email is not valid", false);
					return;
				}

				if (edtRegisterSecurityKey.getText().toString().trim().length() != 4) {
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog.showAlertDialog(context,
							"Security key error!",
							"Security key must be 4 character", false);
					return;
				}

				if (edtRegisterPhone.getText().toString().trim().length() < 4) {
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog
							.showAlertDialog(
									context,
									"Phone Number error!",
									"Phone Number must be more than 5 character length",
									false);
					return;
				}

				String uname = edtRegisterUsername.getText().toString();
				String pass = edtRegisterRepassword.getText().toString();
				String email = edtRegisterEmail.getText().toString();
				String serKey = edtRegisterSecurityKey.getText().toString()
						.trim();
				String phone = edtRegisterPhone.getText().toString().trim();

				mUser = new DatabaseUser(uname, pass, serKey, phone, email);

				// Register with server
				RegisterWithServer taskRegisterWithServer = new RegisterWithServer();
				taskRegisterWithServer.execute(null, null, null);

			}
		});

		btnRegisterBackToLogin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// vflipMain.showPrevious();
				selectPage(0);
			}
		});

	}

	/**
	 * Set function for controls in security form
	 */
	void setFunctionForSecurityForm() {
		for (int i = 0; i < 10; i++) {
			listSecurityImageButton.get(i).setOnClickListener(
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							((Vibrator)getSystemService(VIBRATOR_SERVICE)).vibrate(100);
							securityPass += v.getTag().toString();
							Log.e(TAG, v.getTag().toString() + " "
									+ securityPass);
							if (securityPass.length() == 4) {
								rabtnConfirm1.setChecked(true);
								if (securityPass.equals(mUser.getSecretKey())) {
									Intent intent = new Intent(
											ActivityLogin.this,
											ActivityContactList.class);
									startActivity(intent);
									finish();
									
								} else {
									initSecurityForm();
								}
								
							} else {
								if (securityPass.length() == 1) {
									rabtnConfirm1.setChecked(true);
								}
								if (securityPass.length() == 2) {
									rabtnConfirm2.setChecked(true);
								}
								if (securityPass.length() == 3) {
									rabtnConfirm3.setChecked(true);
								}
								if (securityPass.length() == 4) {
									rabtnConfirm4.setChecked(true);
								}
							}
						}
					});
		}
		
		tvCancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				securityPass = "";
				initSecurityForm();
			}
		});
	}

	void setFunctionForCopyrightForm(){
		linearCopyright.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// postStatusMessage("Testting");
				Intent sharingIntent = new Intent(Intent.ACTION_SEND);
				sharingIntent.setType("text/plain");
				sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT,
						"http://softtech.vn");
				startActivity(Intent
						.createChooser(sharingIntent, "Share using"));
			}
		});
	}
	
	/**
	 * Init main flipper
	 */
	void initViewFlipper() {
		// init animation
		slide_in_left = AnimationUtils.loadAnimation(this,
				android.R.anim.slide_in_left);
		slide_out_right = AnimationUtils.loadAnimation(this,
				android.R.anim.slide_out_right);

		vflipMain.setInAnimation(slide_in_left);
		vflipMain.setOutAnimation(slide_out_right);
	}

	/**
	 * Init Security Form
	 */
	void initSecurityForm() {
		securityPass = "";
		rabtnConfirm1.setChecked(false);
		rabtnConfirm2.setChecked(false);
		rabtnConfirm3.setChecked(false);
		rabtnConfirm4.setChecked(false);
	}

	/**
	 * Select page of main flipper
	 * 
	 * @param page
	 *            : 0 - login 1 - register 2 - security
	 */
	void selectPage(int page) {
		String title_name = "";
		if (mniActionLogout != null) {
			mniActionLogout.setVisible(false);
		}
		try{
			InputMethodManager imm = (InputMethodManager)getSystemService(
					Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		switch (page) {
		case 0:
			title_name = getResources().getString(R.string.title_login);
			break;
		case 1:
			title_name = getResources().getString(R.string.title_register);
			break;
		case 2:
			if (mniActionLogout != null) {
				mniActionLogout.setVisible(true);
			}
			title_name = getResources().getString(R.string.title_security);
			initSecurityForm();
		}
		vflipMain.setDisplayedChild(page);
		this.getActionBar().setTitle(title_name);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_login, menu);

		mniActionLogout = (MenuItem) menu.findItem(R.id.action_log_out);

		// init visible

		mniActionLogout.setVisible(false);

		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_log_out:
			ToolsSaveFile tsf = new ToolsSaveFile();
			tsf.SaveContentFile(context, ConstantsFileName.FILE_ID_LOG_IN, "");
			selectPage(0);
			break;
		default:
			break;
		}
		return true;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (db != null) {
			db.close();
		}
	}

	public boolean isValidEmail(CharSequence target) {
		return !TextUtils.isEmpty(target)
				&& android.util.Patterns.EMAIL_ADDRESS.matcher(target)
						.matches();
	}

	class RegisterWithServer extends AsyncTask<Void, Void, Void> {

		String result_from_server;

		List<NameValuePair> listPair;

		ProgressDialog progressDialog = null;

		public RegisterWithServer() {

			result_from_server = "";

			listPair = new ArrayList<NameValuePair>();
			listPair.add(new BasicNameValuePair(DatabaseUser.KEY_USERNAME,
					mUser.getUsername()));
			listPair.add(new BasicNameValuePair(DatabaseUser.KEY_PASSWORD,
					mUser.getPassword()));
			listPair.add(new BasicNameValuePair(DatabaseUser.KEY_PHONE, mUser
					.getPhoneNumber()));
			listPair.add(new BasicNameValuePair(DatabaseUser.KEY_EMAIL, mUser
					.getEmail()));
			listPair.add(new BasicNameValuePair(DatabaseUser.KEY_SECRET, mUser
					.getSecretKey()));

		}

		@Override
		protected Void doInBackground(Void... params) {
			HttpRequest request = new HttpRequest();
			result_from_server = request.makeServiceCall(
					ConstantsFileName.URL_USER_REGISTER, HttpRequest.POST,
					listPair);
			return null;
		}

		@Override
		protected void onPreExecute() {
			// tien xu ly truoc khi dang ky voi server
			progressDialog = new ProgressDialog(context);
			progressDialog.setMessage("processing...");
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setIndeterminate(true);

			progressDialog.show();

			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(Void result) {

			if (progressDialog != null) {
				progressDialog.dismiss();
			}

			if (result_from_server != null) {

				Log.e("result", result_from_server);

				try {
					JSONObject jsonObj = new JSONObject(result_from_server);

					int success = jsonObj.getInt("success");

					if (success != 0) {
						// register success
						// id user = success

						mUser.set_Id(success);
						db.addUser(mUser);
						ToolsSaveFile tsf = new ToolsSaveFile();
						tsf.SaveContentFile(context,
								ConstantsFileName.FILE_ID_LOG_IN, "" + mUser.get_Id());

						selectPage(2);
					} else {
						// register fail
						int username = jsonObj
								.getInt(DatabaseUser.KEY_USERNAME);

						int password = jsonObj
								.getInt(DatabaseUser.KEY_PASSWORD);

						int email = jsonObj.getInt(DatabaseUser.KEY_EMAIL);

						int phone_number = jsonObj
								.getInt(DatabaseUser.KEY_PHONE);

						int secret_key = jsonObj
								.getInt(DatabaseUser.KEY_SECRET);

						if (username != 2) {

							status_username = false;

							edtRegisterUsername.setTextColor(Color.RED);
						} else {
							edtRegisterUsername.setTextColor(Color.BLACK);
						}

						if (password != 2) {

							status_password = false;

							edtRegisterPassword.setTextColor(Color.RED);
						} else {
							edtRegisterPassword.setTextColor(Color.BLACK);
						}

						if (email != 2) {

							status_email = false;

							edtRegisterEmail.setTextColor(Color.RED);
						} else {
							edtRegisterEmail.setTextColor(Color.BLACK);
						}

						if (phone_number != 2) {

							status_phone = false;

							edtRegisterPhone.setTextColor(Color.RED);
						} else {
							edtRegisterPhone.setTextColor(Color.BLACK);
						}

						if (secret_key != 2) {

							status_secretkey = false;

							edtRegisterSecurityKey.setTextColor(Color.RED);
						} else {
							edtRegisterSecurityKey.setTextColor(Color.BLACK);
						}
					}
				} catch (JSONException e) {

					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog
							.showAlertDialog(
									context,
									"Server error!",
									"Server is having trouble ! Please contact administrator for detail !",
									false);

					e.printStackTrace();
				}
			} else {
				mAlertDialog = new ViewAlertDialogManager();
				mAlertDialog.showAlertDialog(context, "Internet error!",
						"Can not Connect to Server", false);

			}

			super.onPostExecute(result);
		}

	}

	class LoginWithServer extends AsyncTask<Void, Void, Void> {

		List<NameValuePair> listPair;

		String result_from_server = "";

		ProgressDialog progressDialog = null;

		public LoginWithServer(String username, String password) {
			listPair = new ArrayList<NameValuePair>();
			listPair.add(new BasicNameValuePair(DatabaseUser.KEY_USERNAME,
					username));
			listPair.add(new BasicNameValuePair(DatabaseUser.KEY_PASSWORD,
					password));
		}

		@Override
		protected Void doInBackground(Void... params) {
			HttpRequest request = new HttpRequest();
			result_from_server = request.makeServiceCall(
					ConstantsFileName.URL_USER_LOGIN, HttpRequest.POST,
					listPair);
			return null;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = new ProgressDialog(context);
			progressDialog.setMessage("processing...");
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setIndeterminate(true);

			progressDialog.show();
		}

		@Override
		protected void onPostExecute(Void result) {

			if (progressDialog != null) {
				progressDialog.dismiss();
			}

			if (result_from_server == null || result_from_server.equals(null)
					|| result_from_server.equals("")) {
				mAlertDialog = new ViewAlertDialogManager();
				mAlertDialog.showAlertDialog(context, "Request timeout !",
						"Something for work is incorrect ! Please try again !",
						false);
			} else {
				Log.e(TAG, result_from_server);
				try {
					JSONObject jsonObject = new JSONObject(result_from_server);
					int success = jsonObject
							.getInt(ConstantsFileName.success_field);

					if (success == 1) {
						try {
							JSONObject user_info = jsonObject.getJSONArray(
									ConstantsFileName.data_field)
									.getJSONObject(0);
							if (mUser == null) {
								mUser = new DatabaseUser();
							}
							mUser.setDataFromJSON(user_info);
							DatabaseUser temp = db.getUser(mUser.get_Id());
							if (temp != null) {

								db.updateUser(mUser);
							} else {
								db.addUser(mUser);

							}

							ToolsSaveFile tsf = new ToolsSaveFile();
							tsf.SaveContentFile(context,
									ConstantsFileName.FILE_ID_LOG_IN, ""
											+ mUser.get_Id());

							selectPage(2);
						} catch (Exception ex) {
							ex.printStackTrace();
						}

					} else if (success == 0) {
						mAlertDialog = new ViewAlertDialogManager();
						mAlertDialog
								.showAlertDialog(
										context,
										"Input error !",
										jsonObject
												.getString(ConstantsFileName.log_field),
										false);
					}

				} catch (Exception e) {
					e.printStackTrace();
				}

			}

			super.onPostExecute(result);
		}

	}
	
	class ForgotPassword extends AsyncTask<Void, Void, Void>{

		List<NameValuePair> listPair;

		String result_from_server = "";

		ProgressDialog progressDialog = null;
		
		public ForgotPassword(String email) {
			listPair = new ArrayList<NameValuePair>();
			listPair.add(new BasicNameValuePair(DatabaseUser.KEY_EMAIL,
					email));
		}
		
		@Override
		protected Void doInBackground(Void... params) {

			HttpRequest request = new HttpRequest();
			result_from_server = request.makeServiceCall(
					ConstantsFileName.URL_USER_FORGOTPASS, HttpRequest.POST,
					listPair);
			return null;
		}

		@Override
		protected void onPreExecute() {

			super.onPreExecute();
			progressDialog = new ProgressDialog(context);
			progressDialog.setMessage("processing...");
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setIndeterminate(true);

			progressDialog.show();
		}

		@Override
		protected void onPostExecute(Void result) {

			super.onPostExecute(result);
			
			if (progressDialog != null) {
				progressDialog.dismiss();
			}

			if (result_from_server == null || result_from_server.equals(null)
					|| result_from_server.equals("")) {
				mAlertDialog = new ViewAlertDialogManager();
				mAlertDialog.showAlertDialog(context, "Request timeout !",
						"Something for work is incorrect ! Please try again !",
						false);
			}else{
				Log.e(TAG, result_from_server);
				try {
					JSONObject jsonObject = new JSONObject(result_from_server);
					int success = jsonObject
							.getInt(ConstantsFileName.success_field);

					if (success == 1) {
						mAlertDialog = new ViewAlertDialogManager();
						mAlertDialog.showAlertDialog(context, "Success !",
								"An email was send to your email address!",
								false);
					}else{
						mAlertDialog = new ViewAlertDialogManager();
						mAlertDialog.showAlertDialog(context, "Request error !",
								"Something for work is incorrect ! Please try again !",
								false);
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
	
}
